package mspbots.data.sync.jira.receivers;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.data.sync.BaseReceiver;
import mspbots.data.sync.ResultMessageModel;
import mspbots.data.sync.jira.model.JiraChangelogs;
import mspbots.data.sync.jira.model.JiraChangelogsItems;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.relational.core.query.Criteria;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Log4j2
@Component
@RequiredArgsConstructor
public class JiraChangelogsReceiver extends BaseReceiver {

    @RabbitListener(queues = "jira.issuechangelogs.sync")
    public void process(ResultMessageModel model) {
        if (ObjectUtils.isEmpty(model.getEntity()) || !ResultMessageModel.MessageModelAction.ADD.equals(model.getAction())) {
            log.error("jira.changelogs.sync entry is null,or Action No Add");
            return;
        }

        JsonNode node = model.getEntity();
        JiraChangelogs data = JiraChangelogs.builder().otherId(node.get("id").asText()).build();
        data.setExtend(node);
        data.setTenantId(model.getTenantId());
        data.setCreateTime(!ObjectUtils.isEmpty(node.get("created"))
                ? LocalDateTime.parse(node.get("created").asText().substring(0,19), DateTimeFormatter.ISO_DATE_TIME) : null);
        data.setUpdateTime(!ObjectUtils.isEmpty(node.get("updated"))
                ? LocalDateTime.parse(node.get("updated").asText().substring(0,19), DateTimeFormatter.ISO_DATE_TIME) : null);
        data.setSyncTime(LocalDateTime.now());


        this.databaseClient.execute("delete from jira_changelogs_items where tenant_id="+data.getTenantId()
                +" AND other_id ilike '"+data.getOtherId()+"_%' ").fetch().rowsUpdated().subscribe();

        this.databaseClient.execute("SELECT id FROM jira_changelogs WHERE tenant_id =:tenantId AND other_id =:otherId")
                .as(Long.class)
                .bind("tenantId", data.getTenantId())
                .bind("otherId", data.getOtherId())
                .fetch().one()
                .flatMap(id -> {
                    data.setId(id);
                   return this.databaseClient.update().table(JiraChangelogs.class).using(data).fetch().rowsUpdated();
                })
                .switchIfEmpty(this.databaseClient.insert().into(JiraChangelogs.class).using(data).fetch().rowsUpdated())
                .flatMapIterable(id->{return data.getExtend().get("items");})
                .flatMap(item->{
                    JiraChangelogsItems changelogsItem=JiraChangelogsItems.builder().otherId(data.getOtherId()+"_"+System.currentTimeMillis()).build();
                    ObjectNode objectNode = objectMapper.convertValue(item, ObjectNode.class);
                    objectNode.put("change_logs_id",data.getOtherId());
                    changelogsItem.setExtend(objectNode);
                    changelogsItem.setTenantId(data.getTenantId());
                    changelogsItem.setCreateTime(data.getCreateTime());
                    changelogsItem.setUpdateTime(data.getUpdateTime());
                    changelogsItem.setSyncTime(data.getSyncTime());
                    return this.databaseClient.insert().into(JiraChangelogsItems.class).using(changelogsItem).fetch().rowsUpdated();
                })
                .subscribe(result -> log.debug("JiraIssue save is success {}", result),
                        err -> log.error("JiraIssue save or update is error,msg: {}", err.getMessage()));
    }


}
